package models

import (
	"golang.org/x/crypto/bcrypt"
)

type User struct {
	Id       int64  `json:"id" mapstructure:"-"`
	Username string `json:"username" xorm:"unique not null"`
	Password string `json:"-" mapstructure:"-" xorm:"not null"`
	Email    string `json:"email"`
	Gender   int64  `json:"gender"`
	Avatar   string `json:"avatar" xorm:"not null"`
	Address  string `json:"address"`
	Nickname string `json:"nickname"`
	Created  int64  `json:"created" mapstructure:"-" xorm:"created"`
	Updated  int64  `json:"updated" mapstructure:"-" xorm:"updated"`
	Deleted  int64  `json:"deleted" mapstructure:"-" xorm:"deleted"`

	Roles []Role `json:"roles" mapstructure:"-"  xorm:"-"`
}

// 设置密码哈希
func (u *User) SetPassword(password string) error {
	hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(hashed)
	return nil
}

// 验证密码
func (u *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	return err == nil
}

// 钩子函数 - 插入前
func (u *User) BeforeInsert() {
	u.SetPassword(u.Password)
}

// 钩子函数 - 更新前
func (u *User) BeforeUpdate() {
	if !u.CheckPassword(u.Password) {
		u.SetPassword(u.Password)
	}
}
